// pages/CreateArticle/CreateArticle.js
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
const app = getApp()
const db = wx.cloud.database()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        imageList: [],
        title: "",
        article: "",
        area: "日常交流"
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },
    afterRead(event) {
        let that = this
        let imageList = this.data.imageList
        wx.chooseMedia({
            count: 3,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            maxDuration: 30,
            success(res) {
                for ( let i in res.tempFiles ) {
                    imageList.push(res.tempFiles[i].tempFilePath)
                }
                that.setData({imageList})
            }
        })
    },
    deleteImage(e) {
        console.log(e);
        let index = e.currentTarget.index
        let imageList = this.data.imageList
        imageList.splice(index,1)
        this.setData({imageList})
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },
    // 选择版块分区
    selectArea() {
        this.setData({actionsheet:true})
    },
    chooseArea(e) {
        this.setData({
            area:e.currentTarget.dataset.value,
            actionsheet:false
        })
    },
    onClose() {
        this.setData({actionsheet:false});
    },
    publish(e) {
        if (this.data.title.length <= 0) {
            Notify({ type: 'danger', message: '标题不能为空！' });
        } else if (this.data.article.length <= 0) {
            Notify({ type: 'danger', message: '内容不能为空！' });
        } else {
            let that = this
            let imageList = this.data.imageList
            let count = 0
            let cloudImageList = []
            Toast.loading({
                message: '加载中...',
                forbidClick: true,
            })
            wx.cloud.callFunction({
                name: 'checkContent',
                data: {
                    content: this.data.title + this.data.article
                },
                success: (res) => {
                    let suggest = res.result.result.suggest // 审核建议
                    let label = res.result.result.label // 退回原因
                    // 100 正常；10001 广告；20001 时政；20002 色情；20003 辱骂；20006 违法犯罪；20008 欺诈；20012 低俗；20013 版权；21000 其他
                    console.log(suggest)
                    console.log(this.data.title + this.data.article)
                    let reason = {'10001': '广告','20001': '时政','20002': '色情','20003': '辱骂','20006': '犯罪','20008': '欺诈','20012': '低俗','20013': '版权','21000': '不良'}
                    if (suggest != 'pass') {
                        wx.showModal({
                            title: "言论不当！",
                            content: `可能涉及${reason[label]}内容，请修改后再发吧！`,
                            showCancel: false,
                            confirmText: '知道啦',
                            confirmColor: '#f17700'
                        })
                    } else {
                        if (imageList.length > 0) {
                            imageList.map(function(image){
                                wx.cloud.uploadFile({
                                    cloudPath: 'article/' + (new Date()).valueOf() + ".jpg",
                                    filePath: image, // 文件路径
                                }).then(res => { 
                                    console.log(res);
                                    cloudImageList.push(res.fileID)
                                    console.log(imageList.length);
                                    if (++count === imageList.length) {
                                        db.collection("articleDB").add({
                                            data: {
                                                title: that.data.title,
                                                article: that.data.article,
                                                area: that.data.area,
                                                imageList: cloudImageList,
                                                createTime: db.serverDate(),
                                                comment: [],
                                                like: {},
                                                favourite: {}
                                            },
                                            success: (res) => {
                                                console.log(res);
                                                wx.navigateBack()
                                                let id = res._id
                                                wx.request({
                                                    url: 'https://www.drawu.com.cn:25565/comment', //仅为示例，并非真实的接口地址
                                                    method: 'POST',
                                                    header: {
                                                    'content-type': 'application/json' // 默认值
                                                    },
                                                    data: {
                                                        title: that.data.title,
                                                        article: that.data.article,
                                                        imageList: cloudImageList
                                                    },
                                                    success: (res) => {
                                                        let comment = {"openid":'drawu',"content":res.data,"like":{},createTime:db.serverDate()};
                                                        db.collection('articleDB').doc(id).update({
                                                            data: {
                                                                comment: db.command.unshift([comment])
                                                            }
                                                        })
                                                    }
                                                })
                                            },
                                        })
                                    }
                                })
                            })
                        } else {
                            db.collection("articleDB").add({
                                data: {
                                    title: that.data.title,
                                    article: that.data.article,
                                    area: that.data.area,
                                    imageList: [],
                                    comment: [],
                                    createTime: db.serverDate(),
                                    like: {},
                                    favourite: {}
                                    
                                },
                                success: (res) => {
                                    wx.navigateBack()
                                    let id = res._id
                                    wx.request({
                                        url: 'https://www.drawu.com.cn:25565/comment', //仅为示例，并非真实的接口地址
                                        method: 'POST',
                                        header: {
                                            'content-type': 'application/json' // 默认值
                                        },
                                        data: {
                                            title: that.data.title,
                                            article: that.data.article,
                                            imageList: []
                                        },
                                        success: (res) => {
                                            let comment = {"openid":'drawu',"content":res.data,"like":{},createTime:db.serverDate()};
                                            db.collection('articleDB').doc(id).update({
                                                data: {
                                                    comment: db.command.unshift([comment])
                                                }
                                            })
                                        }
                                    })
                                    console.log(res);
                                }
                            })
                        }
                    }
                }
            })
        

        }
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})